/* So, I have cluster of computers with linux, and I think I could use it for this progamm.
 * And I don't want to install SDL and X11 on my server, so I just write another network libary for linux
 */

#ifdef NO_GRAPHIC
#include "net.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

struct Net* N_init(char* addres, int port) {
    struct Net *n = malloc(sizeof(struct Net));
    if(n == NULL) {
        fprintf(stderr, "Unable to allocate memory\n");
        return NULL;
    }
    n->client = socket(AF_INET, SOCK_STREAM, 0);
     if(n->client < 0){
        fprintf(stderr, "Unable to create socket\n");
        return NULL;
    }
    n->remoteIp.sin_family = AF_INET;
    n->remoteIp.sin_port = htons(port);
    n->remoteIp.sin_addr.s_addr = inet_addr(addres);
    if(connect(n->client, (struct sockaddr*)&n->remoteIp, sizeof(n->remoteIp)) < 0) {
        fprintf(stderr, "Unable to connect\n");
    }
    return n;
}

void N_send(struct Net *n, struct Package pkg) {
    if(send(n->client, (char*)(&pkg), sizeof(struct Package), 0) < 0) {
        fprintf(stderr, "N_send failed\n");
    }
}

struct Package N_get(struct Net *n) {
    struct Package pkg = { 0 };
    if(recv(n->client, (char*)(&pkg), sizeof(struct Package), 0) < 0) {
        fprintf(stderr, "Package recive failed\n");
    }
    return pkg;
}

void N_close(struct Net *n) {
    struct Package pkg = (struct Package){.type = P_CLOSE};
    N_send(n, pkg);
    n->active = false;
    close(n->client);
    if(n != NULL || n->active) {
        free(n);
        n = NULL;
    }
}
#endif
